//
//  FKHomeVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/13.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKHomeVC.h"
#import "FKTabBarVC.h"
#import "FKTableCell.h"
#import "FKHomeBannerCell.h"
#import "FKHomeCategoryCell.h"
#import "FKHomeArticleCell.h"
#import "FKHomeNewCell.h"
#import "FKHomeHotCell.h"
#import "FKHomeSectionHeader.h"
#import "FKHomeGoods.h"
#import "FKCustomBtn.h"
#import "FKInformationListVC.h"
#import "FKSearchVC.h"
#import "FKCommodityDetailVC.h"
#import "FKShoppingCartVC.h"
#import "FKChooseCityVC.h"
#import "FKLocationManager.h"
#import "FKBusinessGiftBagVC.h"
#import "FKHomeCouponPopView.h"
#import "FKHomeCoupon.h"
#import "FKHotBuinessCell.h"
#import <AFNetworking/AFNetworking.h>
#import "FKHotBuinessViewController.h"

static NSString *const bannerId = @"FKHomeBannerCell";
static NSString *const categoryId = @"FKHomeCategoryCell";
static NSString *const gongGaoId = @"FKHomeArticleCell";
static NSString *const hotbusinessId = @"FKHotBuinessCell";
static NSString *const newId = @"FKHomeNewCell";
static NSString *const hotId = @"FKHomeHotCell";
static NSString *const headerId = @"FKHomeSectionHeader";


@interface FKHomeVC ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, FKHomeArticleCellDelegate, FKHomeCategoryCellDelegate>

@property (nonatomic, weak) FKCustomBtn *cityItem;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSMutableDictionary *param;
@property(nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *tel;
/** 选择的站点城市 */
@property (nonatomic, strong) NSDictionary *selectedSite;
@property (nonatomic, weak) UILabel *cartNumLabel;

/** 因为爆款要做分页，所以要单独把爆款的数据存起来 */
@property (nonatomic, strong) NSMutableArray *hotItems;

@end

@implementation FKHomeVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
//        _datas = @[@{@"items" : @[@{@"cellName" : @"FKHomeHeaderCell",
//                                    @"cellSize" : @(CGSizeMake(fkScreenW, fk_adjustW(340))),
//                                    @"data" : @""
//                                    }]}];
    }
    return _datas;
}

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
        _param[@"pagesize"] = @(10);
    }
    return _param;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateCartNum:(NSNotification *)noti
{
    NSDictionary *data = noti.userInfo;
    self.cartNumLabel.text = fkFORMAT(@"%@", data[@"cartNum"]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCartNum:) name:@"updateCartNum" object:nil];
    
    UIButton *searchBtn = [UIButton fk_btnWithTarget:self action:@selector(searchBtnClicked) font:fk_adjustFont(13) normalTitle:@"请输入关键词搜索" normalTitleColor:fkColor999999 selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"nav_search"] selectedImg:nil bgImg:nil selectedBgImg:nil];
    [searchBtn fk_viewCornerRadius:fk_adjustW(15) borderWidth:0 borderColor:nil];
    searchBtn.backgroundColor = fkColorECECEC;
    searchBtn.bounds = CGRectMake(0, 0, fk_adjustW(250), fk_adjustW(30));
    searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, fk_adjustW(6), 0, 0);
    searchBtn.contentEdgeInsets = UIEdgeInsetsMake(0, fk_adjustW(12), 0, 0);
    self.navigationItem.titleView = searchBtn;

    FKCustomBtn *cityItem = [FKCustomBtn fk_btnWithTarget:self action:@selector(cityItemClicked) font:fk_adjustFont(15) normalTitle:@"定位中" normalTitleColor:fkColor333333 selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"arrow_down"] selectedImg:nil bgImg:nil selectedBgImg:nil];
    cityItem.frame = CGRectMake(0, 0, fk_adjustW(65), fkNavBarH);
    cityItem.imagePosition = FKImagePositionRight;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cityItem];
    self.cityItem = cityItem;

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem fk_itemWithImageName:@"Customerservice" highImageName:@"Customerservice" target:self action:@selector(righItemClicked)];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.alwaysBounceVertical = true;
    collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
//    collectionView.contentInset = UIEdgeInsetsMake(0, 0, fkTabBarH, 0);
    collectionView.contentInset = UIEdgeInsetsMake(0, 0, 8, 0);
    [collectionView registerClass:[FKHomeBannerCell class] forCellWithReuseIdentifier:bannerId];
    [collectionView registerClass:[FKHomeCategoryCell class] forCellWithReuseIdentifier:categoryId];
    [collectionView registerClass:[FKHomeArticleCell class] forCellWithReuseIdentifier:gongGaoId];
    [collectionView registerClass:[FKHotBuinessCell  class] forCellWithReuseIdentifier:hotbusinessId];
    [collectionView registerClass:[FKHomeNewCell class] forCellWithReuseIdentifier:newId];
    [collectionView registerClass:[FKHomeHotCell class] forCellWithReuseIdentifier:hotId];
    [collectionView registerClass:[FKHomeSectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];

    
    UIButton *cartBtn = [UIButton fk_btnWithTarget:self action:@selector(cartBtnClicked) img:[UIImage imageNamed:@"Shoppingcartempty"]];
    [self.view addSubview:cartBtn];
    [cartBtn setImage:[UIImage imageNamed:@"ShoppingCart"] forState:UIControlStateSelected];
    
    UILabel *cartNumLabel = [UILabel fk_labelWithFont:[UIFont systemFontOfSize:10] textColor:[UIColor whiteColor] textAlignment:NSTextAlignmentCenter];
    [cartBtn addSubview:cartNumLabel];
    self.cartNumLabel = cartNumLabel;
    cartNumLabel.backgroundColor = fkMainColor;
    [cartNumLabel fk_viewCornerRadius:6 borderWidth:0 borderColor:nil];

    [cartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-12);
        make.width.height.mas_equalTo(fk_adjustW(40));
        make.bottom.offset(-fkTabBarH-fkOffsetBottom);
    }];
    [cartNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(12);
        make.right.top.equalTo(cartBtn);
    }];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.offset(-fkTabBarH);
    }];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    fkWeakSelf(self);
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //        NSLog(@"当前网络状态：%zd", status);
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                [weakself.collectionView.mj_header beginRefreshing];
                // 获取定位城市
                [[FKLocationManager sharedLocation] getCity:^(NSString *addressString) {
                    if (weakself.selectedSite) {
                        [weakself.cityItem setTitle:weakself.selectedSite[@"title"] forState:UIControlStateNormal];
                    } else {
                        [weakself.cityItem setTitle:addressString forState:UIControlStateNormal];
                    }
                }];
            }
                break;
            default:
                break;
        }
    }];
}

#pragma mark - action
- (void)searchBtnClicked
{
    FKSearchVC *vc = [[FKSearchVC alloc] init];
    fkPushNav(vc);
}

- (void)cityItemClicked
{
    FKChooseCityVC *vc = [[FKChooseCityVC alloc] init];
    fkPushNav(vc);
    fkWeakSelf(self);
    vc.chooseCityBlock = ^(NSDictionary * _Nonnull cityInfo) {
        weakself.selectedSite = cityInfo;
        [weakself.cityItem setTitle:weakself.selectedSite[@"title"] forState:UIControlStateNormal];
        weakself.param[@"area_id"] = weakself.selectedSite[@"id"];
        [weakself loadData];
    };
}

- (void)righItemClicked
{
    if (self.tel) {
        fk_call(self.tel);
    } else {
        [SVProgressHUD showInfoWithStatus:@"数据加载中，请稍后"];
    }
}

- (void)cartBtnClicked
{
    [FKLoginTool checkLogin:^{
        FKShoppingCartVC *vc = [[FKShoppingCartVC alloc] init];
        fkPushNav(vc);
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.datas.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    NSArray *items = group[@"items"];
    return items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.item];
    FKCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:item[@"cellName"] forIndexPath:indexPath];
    cell.data = item[@"data"];
    cell.delegate = self;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        FKHomeSectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        NSDictionary *group = self.datas[indexPath.section];
        header.data = group[@"data"];
        return header;
    }
    return nil;
}

#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.item];
    return [item[@"cellSize"] CGSizeValue];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"headerSize"] ? [group[@"headerSize"] CGSizeValue] : CGSizeZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"margin"] ? [group[@"margin"] floatValue] : 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"margin"] ? [group[@"margin"] floatValue] : 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    NSDictionary *group = self.datas[section];
    return group[@"inset"] ? UIEdgeInsetsMake(0, 12, 0, 12) : UIEdgeInsetsZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    NSDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSDictionary *item = items[indexPath.item];
    FKHomeGoods *model = item[@"data"];
    if ([item[@"cellName"] isEqualToString:@"FKHotBuinessCell"]) {
        FKHotBuinessViewController *VC = [FKHotBuinessViewController new];
        VC.ls_title = model.name;
        VC.ID =  model.id;
        fkPushNav(VC);
    }else{
       FKCommodityDetailVC *vc = [[FKCommodityDetailVC alloc] init];
       vc.itemId = model.id;
       fkPushNav(vc);
    }
   
}

#pragma mark - FKHomeArticleCellDelegate
- (void)homeArticleCell:(FKHomeArticleCell *)cell didClickedArticle:(NSString *)articleId
{
    FKInformationListVC *vc = [[FKInformationListVC alloc] init];
    fkPushNav(vc);
}

#pragma mark - FKHomeCellDelegate
- (void)homeCell:(FKTableCell *)cell didClickedPromotionBtn:(UIButton *)btn
{
//    NSString *title = btn.titleLabel.text;
//    if ([title isEqualToString:@"立即购买"]) {
        FKCommodityDetailVC *vc = [[FKCommodityDetailVC alloc] init];
        FKHomeGoods *goods = (FKHomeGoods *)cell.data;
        vc.itemId = goods.id;
        fkPushNav(vc);
//    } else if ([title isEqualToString:@"立即推广"]) {
//
//    }
}

#pragma mark - FKHomeCategoryCellDelegate
- (void)homeCategoryCell:(FKHomeCategoryCell *)cell didSelectedItem:(NSDictionary *)item
{
    NSString *title = item[@"name"];
    NSString *isActive = item[@"is_theme_activity"];
    if ([title isEqualToString:@"创业礼包"]) {
        FKBusinessGiftBagVC *vc = [[FKBusinessGiftBagVC alloc] init];
        vc.title = title;
        fkPushNav(vc);
    } else if ([isActive boolValue]) {
        FKBusinessGiftBagVC *vc = [[FKBusinessGiftBagVC alloc] init];
        vc.title = title;
        vc.active = true;
        vc.item_cate_id = item[@"id"];
        fkPushNav(vc);
    } else {
        [FKCacheTool saveCateItem:item];
        self.tabBarController.selectedIndex = 1;
    }
}

#pragma mark - 网络请求
- (void)loadData
{
    self.page = 1;
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=index" param:self.param success:^(FKBaseResult *result) {
        [self.collectionView.mj_header endRefreshing];
        if (result.isSuccess) {
            
            self.cartNumLabel.text = fkFORMAT(@"%@", result.data[@"cart_num"]);
            self.tel = result.data[@"tel"];
            NSArray *banners = result.data[@"ad"];
            NSArray *categories = result.data[@"item_cate"];
//            NSArray *article = result.data[@"article"];
            
            NSArray *new_item = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"new_item"]];
            NSArray *hot_item = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"hot_item"]];
            NSArray *hot_business = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"pop_spec_subs"]];
            if ([result.data[@"coupon_is_read"] isEqualToNumber:@(1)]) { // 有优惠券
                NSArray *couponList = result.data[@"coupon_list"];
                FKHomeCouponPopView *view = [[FKHomeCouponPopView alloc] init];
                view.datas = [FKHomeCoupon mj_objectArrayWithKeyValuesArray:couponList];;
                [view show];
            }
            
            NSMutableArray *datas = [NSMutableArray array];
            self.datas = datas;
            if (hot_item.count > 0) self.page++;
            
            // 头部
            NSMutableDictionary *bannerGroup = [NSMutableDictionary dictionary];
            [datas addObject:bannerGroup];

            
            NSMutableDictionary *bannerItem = [NSMutableDictionary dictionary];
            bannerItem[@"cellName"] = @"FKHomeBannerCell";
            bannerItem[@"cellSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(188)));
            bannerItem[@"data"] = banners;

            NSMutableDictionary *categoryItem = [NSMutableDictionary dictionary];
            categoryItem[@"cellName"] = @"FKHomeCategoryCell";
            categoryItem[@"cellSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(82)));
            categoryItem[@"data"] = categories;

            NSMutableArray *headerItems = [NSMutableArray array];
            [headerItems addObject:bannerItem];
            [headerItems addObject:categoryItem];
            bannerGroup[@"items"] = headerItems;
            
//            // 公告
//            NSMutableDictionary *gongGaoGroup = [NSMutableDictionary dictionary];
//            [datas addObject:gongGaoGroup];
//            gongGaoGroup[@"headerSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(10)));
//
//
//            NSMutableDictionary *gongGaoItem = [NSMutableDictionary dictionary];
//            gongGaoGroup[@"items"] = @[gongGaoItem];
//            gongGaoItem[@"cellName"] = @"FKHomeArticleCell";
//            gongGaoItem[@"cellSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(60)));
//            gongGaoItem[@"data"] = article;
            
            //热门商圈
            if (hot_business.count > 0) {
                NSMutableDictionary *hotBusinessGroup = [NSMutableDictionary dictionary];
                [datas addObject:hotBusinessGroup];
                hotBusinessGroup[@"headerSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(46)));
                hotBusinessGroup[@"data"] = @"home_title_rmsq";
                
                NSMutableArray *hotbusinessItems = [NSMutableArray array];
                CGFloat hotItemW = (fkScreenW)/3;
                for (FKHomeGoods *model in hot_business) {
                    NSMutableDictionary *hotbusinessItem = [NSMutableDictionary dictionary];
                    [hotbusinessItems addObject:hotbusinessItem];
                    hotbusinessItem[@"cellName"] = @"FKHotBuinessCell";
                    hotbusinessItem[@"cellSize"] = @(CGSizeMake(hotItemW,fk_adjustW(60)));
                    hotbusinessItem[@"data"] = model;
                }
                hotBusinessGroup[@"items"] = hotbusinessItems;
                
            }
            // 爆款
            if (hot_item.count > 0) {
                NSMutableDictionary *hotGroup = [NSMutableDictionary dictionary];
                [datas addObject:hotGroup];
                hotGroup[@"headerSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(46)));
                hotGroup[@"data"] = @"Explosives";
                hotGroup[@"margin"] = @(fk_adjustW(10));
                hotGroup[@"inset"] = @(true);
                
                NSMutableArray *hotItems = [NSMutableArray array];
                CGFloat hotItemW = (fkScreenW - 24 - fk_adjustW(10)) * 0.5 - 0.5;
                for (FKHomeGoods *model in hot_item) {
                    NSMutableDictionary *hotItem = [NSMutableDictionary dictionary];
                    [hotItems addObject:hotItem];
                    hotItem[@"cellName"] = @"FKHomeHotCell";
                    hotItem[@"cellSize"] = @(CGSizeMake(hotItemW, fk_adjustW(250)));
                    hotItem[@"data"] = model;
                }
                hotGroup[@"items"] = hotItems;
            }
            
           // 新品
            if (new_item.count > 0) {
                NSMutableDictionary *newGroup = [NSMutableDictionary dictionary];
                [datas addObject:newGroup];
                newGroup[@"headerSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(46)));
                newGroup[@"data"] = @"Newproducts";
               
                NSMutableArray *newItems = [NSMutableArray array];
                for (FKHomeGoods *model in new_item) {
                    NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
                    [newItems addObject:newItem];
                    newItem[@"cellName"] = @"FKHomeNewCell";
                    newItem[@"cellSize"] = @(CGSizeMake(fkScreenW, fk_adjustW(140)));
                    newItem[@"data"] = model;
                }
                newGroup[@"items"] = newItems;
            }
        }

        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=index" param:self.param success:^(FKBaseResult *result) {
        [self.collectionView.mj_footer endRefreshing];
        if (result.isSuccess) {
            NSArray *newHotItems = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"hot_item"]];
            if (newHotItems.count > 0) {
//                NSMutableArray *array = [NSMutableArray arrayWithArray:self.datas];
//                [array addObjectsFromArray:newArray];
//                self.datas = array;
                
                
                NSMutableArray *items = [NSMutableArray array];
                CGFloat hotItemW = (fkScreenW - 24 - fk_adjustW(10)) * 0.5 - 0.5;
                for (FKHomeGoods *model in newHotItems) {
                    NSMutableDictionary *hotItem = [NSMutableDictionary dictionary];
                    [items addObject:hotItem];
                    hotItem[@"cellName"] = @"FKHomeHotCell";
                    hotItem[@"cellSize"] = @(CGSizeMake(hotItemW, fk_adjustW(250)));
                    hotItem[@"data"] = model;
                }
                if (self.hotItems) {
                    [items insertObjects:self.hotItems atIndexes:[NSIndexSet indexSetWithIndex:0]];
                    NSLog(@"------");
                }
                
                
                [self.collectionView reloadData];
                self.page++;
            } else {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSError *error) {
        [self.collectionView.mj_footer endRefreshing];
    }];
}



@end
